import * as THREE from '../../build/three.module.js';
import { OrbitControls } from '../../jsm/controls/OrbitControls.js';

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf0f0f0);

const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 1, 10000);
camera.position.set(0, -400, 600);

const loader = new THREE.FontLoader();
loader.load('../../fonts/helvetiker_regular.typeface.json', font => {
  const color = 0x006699;
  const mtlDark = new THREE.LineBasicMaterial({
    color: color,
    side: THREE.DoubleSide
  });
  const mtlLight = new THREE.MeshBasicMaterial({
    color: color,
    transparent: true,
    opacity: .4,
    side: THREE.DoubleSide
  });
  const message = 'three.js\nSimple text.';
  const shapes = font.generateShapes(message, 100);
  const gmt = new THREE.ShapeBufferGeometry(shapes);
  gmt.computeBoundingBox();
  let xMid = -.5 * (gmt.boundingBox.max.x - gmt.boundingBox.min.x);
  gmt.translate(xMid, 0, 0);

  // 普通形状
  const text = new THREE.Mesh(gmt, mtlLight);
  text.position.z = -150;
  scene.add(text);

  // 线框形状
  const holeShapes = [];
  for(let i = 0; i < shapes.length; i += 1) {
    const shape = shapes[i];
    if (shape.holes && shape.holes.length > 0) {
      for(let j = 0; j < shape.holes.length; j += 1) {
        const hole = shape.holes[j];
        holeShapes.push(hole);
      }
    }
  }

  shapes.push.apply(shapes, holeShapes);
  
  const lineText = new THREE.Object3D();
  for(let i = 0; i < shapes.length; i += 1) {
    const shape = shapes[i];
    const points = shape.getPoints();
    const gmt = new THREE.BufferGeometry().setFromPoints(points);
    gmt.translate(xMid, 0, 0);
    const lineMesh = new THREE.Line(gmt, mtlDark);
    lineText.add(lineMesh);
  }

  scene.add(lineText);
});

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
controls.update();

const render = () => {
  renderer.render(scene, camera);
}

const animate = () => {
  requestAnimationFrame(animate);
  render();
}
animate();

const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener('resize', handleWindowResize, false);
